<template>
	<view class="chart-cont"><l-echart class="chart" ref="chartRef"></l-echart></view>
</template>
<script setup lang="ts">
	import { onMounted, ref, reactive } from 'vue';
	const echarts = require('../../../uni_modules/lime-echart/static/echarts.min');
	import * as energy from "@/api/energy.ts";
	const chartRef = ref(null);
	const myChart = ref(null);
	const xBarData = ref([]);
	const yBarData = ref([]);
	const option = reactive({
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				//阴影指示器
				type: 'shadow'
			},
			confine: true
		},
		legend: {
			top: 10,
			left: "center",
			itemWidth: 10,
			itemHeight: 5,
			data: ['耗电1'],
		},
		grid: {
			top: 40,
			left: 20,
			right: 10,
			bottom: 20,
			containLabel: true,
		},
		xAxis: [
			{
				type: 'value',
				// min: 0,
				// max: 50,
				// interval: 5,
				axisLabel: {
					show: false
				},
				axisLine: {
					show: false,
				},
				splitLine: {
					show: false,
				},
			}
		],
		yAxis: [
			{
				type: 'category',
				axisTick: {
					show: false
				},
				axisLine: {
					show: false,
				},
				axisLabel: {
					color: '#666'
				},
				splitLine: {
					show: false,
				},
				data: xBarData.value,
			},
		],
		series: [
			{
				name: '耗电1',
				type: 'bar',
				barWidth: 10,
				label: {
					show: true,
					color: "#999",
					position: 'right',
				},
				tooltip: {
					valueFormatter: function (value) {
						return value;
					},
				},
				itemStyle: {
					color: "#BCCAFA",
					borderColor: "#5F83F9",
					borderWidth: 1,
				},
				data: yBarData.value,
			},
		]
	});

	onMounted(() => {
		// // 组件能被调用必须是组件的节点已经被渲染到页面上
		// setTimeout(() => {
		// 	initChart()
		// }, 300)
	});

	async function initChart() {
		if (!chartRef.value) return
		const chart = await chartRef.value.init(echarts)
		chart.setOption(option)
		myChart.value = chart
	}

	const initData = (key, xData, yData) => {

		if (key == energy.GartherType.dwpfmdf) {
			option.series[0].name = "电费"
			option.series[0].tooltip = {
				valueFormatter: function (value) {
					return `${value}元`;
				},
			}
			option.legend.data[0] = "电费"
		} else {
			option.series[0].name = "耗能"
			option.series[0].tooltip = {
				valueFormatter: function (value) {
					return `${value}kw.h`;
				},
			}
			option.legend.data[0] = "耗能"
		}

		xBarData.value.length = 0;
		yBarData.value.length = 0;
		xData.forEach(item => {
			xBarData.value.push(item.name)
			if (yData[`50_0_${item.id}_${key}`] != null && yData[`50_0_${item.id}_${key}`].length > 0) {
				yBarData.value.push(yData[`50_0_${item.id}_${key}`][0].value)
			} else {
				yBarData.value.push(0)
			}

		})

		// 组件能被调用必须是组件的节点已经被渲染到页面上
		setTimeout(() => {
			initChart()
		}, 300)
	}

	defineExpose({
		initData
	})
</script>
<style lang="scss" scoped>
	.chart-cont {
		position: relative;
		width: 100%;
		height: 100%;

		.chart {
			width: 100%;
			height: 100%;
		}
	}
</style>